package com.cn.intelligence.resetful.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.cn.intelligence.mapper.AreasMapper;
import com.cn.intelligence.mapper.CitiesMapper;
import com.cn.intelligence.mapper.ProvincesMapper;
import com.cn.intelligence.mapper.TbAddressMapper;
import com.cn.intelligence.mapper.TbCartMapper;
import com.cn.intelligence.mapper.TbItemMapper;
import com.cn.intelligence.mapper.TbOrderMapper;
import com.cn.intelligence.mapper.TbUserMapper;
import com.cn.intelligence.pojo.Areas;
import com.cn.intelligence.pojo.AreasExample;
import com.cn.intelligence.pojo.Cities;
import com.cn.intelligence.pojo.CitiesExample;
import com.cn.intelligence.pojo.Provinces;
import com.cn.intelligence.pojo.ProvincesExample;
import com.cn.intelligence.pojo.TaotaoResult;
import com.cn.intelligence.pojo.TbAddress;
import com.cn.intelligence.pojo.TbAddressExample;
import com.cn.intelligence.pojo.TbCart;
import com.cn.intelligence.pojo.TbCartExample;
import com.cn.intelligence.pojo.TbItem;
import com.cn.intelligence.pojo.TbItemExample;
import com.cn.intelligence.pojo.TbOrder;
import com.cn.intelligence.pojo.TbOrderExample;
import com.cn.intelligence.pojo.TbUser;
import com.cn.intelligence.pojo.TbUserExample;
import com.cn.intelligence.pojo.WxPayRequest;
import com.cn.intelligence.pojo.WxPayRespones;
import com.cn.intelligence.resetful.pojo.WxUserSerctBean;
import com.cn.intelligence.resetful.service.UserOrderService;
import com.cn.intelligence.util.HttpNetClient;
import com.cn.intelligence.util.IDUtils;
import com.cn.intelligence.util.JsonUtils;
import com.cn.intelligence.util.WxPayServer;
import com.github.pagehelper.PageHelper;
/**
 * 用户订单管理信息
 * @author Administrator
 *
 */
@Service
public class UserOrderServiceImpl implements UserOrderService {

	@Autowired
	public TbOrderMapper tbOrderMapper;
	@Autowired
	public TbAddressMapper tbAddressMapper;
	@Autowired
	public TbUserMapper tbUsetMapper;
	@Autowired
	public TbCartMapper tbCartMapper;
	@Autowired
	public TbItemMapper tbItemMapper;
	@Autowired
	private ProvincesMapper provincesMapper;
	@Autowired
	private CitiesMapper citiesMapper;
	@Autowired
	private AreasMapper areasMapper;
	@Autowired
	private TbUserMapper tbUserMapper;
	
	//
    @Value("${APPID}")
    private String APPID;
    @Value("${MCHID}")
    private String MCHID;
    @Value("${MCHKEY}")
    private String MCHKEY;
    @Value("${NOTIFY_URL}")
    private String NOTIFY_URL;
    @Value("${SECRET}")
    private String SECRET;
    

	@Override
	public List<Provinces>  selectProvinces(String name, String provinceId) {
		
		ProvincesExample provincesExample = new ProvincesExample();
		ProvincesExample.Criteria criteria = provincesExample.createCriteria();
		
		if(name!=null && !"".equals(name)){
			criteria.andProvinceLike(name);
		}
		if(provinceId!=null && !"".equals(provinceId)){
			criteria.andProvinceidEqualTo(provinceId);
		}
		 List<Provinces>  list = provincesMapper.selectByExample(provincesExample);
		return list;
	}

	@Override
	public List<Cities> selectCities(String name, String provinceId) {
		
		CitiesExample citiesExample = new CitiesExample();
		CitiesExample.Criteria criteria = citiesExample.createCriteria();
		
		if(name!=null && !"".equals(name)){
			criteria.andCityLike(name);
		}
		if(provinceId!=null && !"".equals(provinceId)){
			criteria.andProvinceidEqualTo(provinceId);
		}
		 List<Cities>  list = citiesMapper.selectByExample(citiesExample);
		return list;
	}

	@Override
	public List<Areas> selectAreas(String name, String cityId) {
		
		AreasExample areasExample = new AreasExample();
		AreasExample.Criteria criteria = areasExample.createCriteria();
		
		if(name!=null && !"".equals(name)){
			criteria.andAreaLike(name);
		}
		if(cityId!=null && !"".equals(cityId)){
			criteria.andCityidEqualTo(cityId);
		}
		 List<Areas>  list = areasMapper.selectByExample(areasExample);
		return list;
	}
	
	/**
	 * 获取用户订单信息
	 */
	@Override
	public Map<String,Object> getOrderInfo(Long userid, String orderStatus, int page, int rows) {
		Map<String,Object>  map = new HashMap<String,Object>();
		List<Map<String,Object>> resultlist = new ArrayList<Map<String,Object>>();
		// 查询商品信息
		TbOrderExample orderexample = new TbOrderExample();
		orderexample.setOrderByClause(" create_time DESC");
		TbOrderExample.Criteria criteria = orderexample.createCriteria();
		criteria.andUserIdEqualTo(userid);
		if("receive".equals(orderStatus)){
			List<Integer> statuslist = new ArrayList<Integer>();
			statuslist.add(2);
			statuslist.add(3);
			statuslist.add(4);
			criteria.andStatusIn(statuslist);	

		}else if("finish".equals(orderStatus)){
			List<Integer> statuslist = new ArrayList<Integer>();
			statuslist.add(5);
			statuslist.add(6);
			criteria.andStatusIn(statuslist);	
		}else if("deliver".equals(orderStatus)){
			List<Integer> statuslist = new ArrayList<Integer>();
			statuslist.add(2);
			statuslist.add(3);
			criteria.andStatusIn(statuslist);
		}else if("backmoney".equals(orderStatus)){
			List<Integer> statuslist = new ArrayList<Integer>();
			statuslist.add(7);
			statuslist.add(8);
			criteria.andStatusIn(statuslist);
		}else{
			criteria.andStatusEqualTo(1);	
		}
		PageHelper.startPage(page,rows);
		
		 List<TbOrder>  orderList = tbOrderMapper.selectByExampleWithBLOBs(orderexample);
		 
		 // 根据订单编号获取商品信息
		 for (TbOrder tbOrder : orderList) {
			 // 获取购物车信息
			 TbCartExample cartExample = new TbCartExample();
			 TbCartExample.Criteria cartcriteria = cartExample.createCriteria();
			 List<Long> cartIdlist = new ArrayList<Long>();
			 if(tbOrder.getCartId()!=null && !"".equals(tbOrder.getCartId())){
				String cartIds[]=tbOrder.getCartId().split(",");
				for (String cartId : cartIds) {
					cartIdlist.add(Long.parseLong(cartId));
				}
				 
			 }
			 cartcriteria.andIdIn(cartIdlist);
			 List<TbCart> tbcartlist = tbCartMapper.selectByExample(cartExample);
			 
			 
			 int num = 0;
			 for (TbCart tbCart2 : tbcartlist) {
				 num += Integer.parseInt(tbCart2.getNum());
			 }
					TbItemExample example = new TbItemExample();
					TbItemExample.Criteria cr= example.createCriteria();
					cr.andIdEqualTo(tbcartlist.get(0).getPid());
					List<TbItem> item = tbItemMapper.selectByExampleWithBLOBs(example);
					Map<String,Object> mapOrder = new HashMap<String, Object>();
					mapOrder.put("photo_x", item.get(0).getPhotoX()==null || "".equals(item.get(0).getPhotoX())?"":item.get(0).getPhotoX().split(",")[0]);
					mapOrder.put("orderid", tbOrder.getOrderId());
					mapOrder.put("price", tbOrder.getPayment());
					mapOrder.put("product_num", num);
					mapOrder.put("pro_count", tbcartlist.size());
					mapOrder.put("id", tbOrder.getOrderId());
					mapOrder.put("order_sn",tbOrder.getOrderId());
					mapOrder.put("type",tbOrder.getPaymentType());
					String desc="退款申请中";
					if(tbOrder.getStatus()==7){
						desc="退款申请中";
					}else if(tbOrder.getStatus()==8){
						desc="退款完成";
					}else{
						desc="订单执行中";
					}
					
					mapOrder.put("desc",desc);
					resultlist.add(mapOrder);
			//}			
		}
		map.put("orderInfo", resultlist);
		
		return map;
	}
	/**
	 * 获取用户收货地址
	 * @return
	 */
	@Override
	public Map<String, Object> getAddressInfo(Long userid) {
		Map<String,Object>  map = new HashMap<String,Object>();
		// 查询商品信息
		TbAddressExample addressexample = new TbAddressExample();
		TbAddressExample.Criteria criteria = addressexample.createCriteria();
		criteria.andUidEqualTo(userid);
		 List<TbAddress>  addressList = tbAddressMapper.selectByExample(addressexample);
		map.put("address", addressList);
		
		return map;
	}
	/**
	 * 获取用户oppenid,如果没有的改用户则保存改用户信息
	 */
	@Override
	public Map<String, Object> getsessionkey(String code, String sessionId) {
		
		String httpurl  = "https://api.weixin.qq.com/sns/jscode2session?";//?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
		httpurl+="appid="+APPID+"&secret="+SECRET+"&js_code="+code+"&grant_type=authorization_code";
		String result = HttpNetClient.GET(httpurl);
		WxUserSerctBean b = new WxUserSerctBean();
		b = JsonUtils.jsonToPojo(result, b.getClass());
		
		Map<String,Object> map = new HashMap<String,Object>();
		// 生产openid
		String openId =b.getOpenid();
		// 查询改用户是否存在
		TbUserExample example = new TbUserExample();
		TbUserExample.Criteria criteria = example.createCriteria();
		criteria.andOpenidEqualTo(openId);
		 List<TbUser> tbuserlist = tbUsetMapper.selectByExample(example);
		 if(tbuserlist.size()==1){
			 // 如果存在就返回改用户信息
			 tbuserlist.get(0).setExited(false);
			map.put("tbuser", tbuserlist.get(0));
		 }else{
			 TbUser tbuser = new TbUser();
			 tbuser.setId(IDUtils.genItemId());
			 tbuser.setOpenid(openId);
			 tbuser.setSessionid(b.getSession_key());
			 tbuser.setGender(1);
			 tbuser.setCreated(new Date());
			 tbuser.setUpdated(new Date());
			 tbuser.setExited(true);
			int value =  tbUsetMapper.insert(tbuser);
			if(value == 1){
				map.put("tbuser", tbuser);
			}else{
				map.put("tbuser", null);
			}
		 }
		
		return map;
	}
	@Override
	public Map<String, Object> authlogin(TbUser tbuser) {
		
		Map<String,Object> map = new HashMap<String,Object>();
		// 查询改用户是否存在
		TbUserExample example = new TbUserExample();
		TbUserExample.Criteria criteria = example.createCriteria();
		criteria.andOpenidEqualTo(tbuser.getOpenid());
		criteria.andSessionidEqualTo(tbuser.getSessionid());
		 List<TbUser> tbuserlist = tbUsetMapper.selectByExample(example);
		 if(tbuserlist.size()==1){
			 TbUser newUser = tbuserlist.get(0);
			 newUser.setUpdated(new Date());
			int value =  tbUsetMapper.updateByExampleSelective(tbuser, example);
			if(value == 1){
				map.put("tbuser", newUser);
			}else{
				map.put("tbuser", null);
			}
		 }
		
		return map;
	}
	/**
	 * 添加地址
	 */
	@Override
	public TbAddress addAddressInfo(TbAddress tbAddress) {
		Integer id = (int) IDUtils.genItemId();
		tbAddress.setId(id);
		tbAddress.setCreated(new Date());
		tbAddress.setIsDefault("0");
		tbAddress.setUpdated(new Date());
		int value = tbAddressMapper.insertSelective(tbAddress);
		if(value == 1){
			return tbAddress;
		}else{
			return null;
		}  
	}
	/**
	 * 修改地址
	 * @throws Exception 
	 */
	@Override
	public TbAddress updateAddressInfo(TbAddress tbAddress) throws Exception {
		
		// 修改当前的为非默认信息
		TbAddress tbAddressold = new TbAddress();
		TbAddressExample addressold = new TbAddressExample();
		TbAddressExample.Criteria criteriaold = addressold.createCriteria();
		criteriaold.andUidEqualTo(tbAddress.getUid());
		tbAddressold.setUpdated(new Date());
		tbAddressold.setIsDefault("0");
		int valueold = tbAddressMapper.updateByExampleSelective(tbAddressold, addressold);
		if(valueold<=0){
			 throw  new Exception();
		}
		TbAddressExample addressexample = new TbAddressExample();
		TbAddressExample.Criteria criteria = addressexample.createCriteria();
		criteria.andUidEqualTo(tbAddress.getUid());
		criteria.andIdEqualTo(tbAddress.getId());
		tbAddress.setUpdated(new Date());		
		int value = tbAddressMapper.updateByExampleSelective(tbAddress, addressexample);
		if(value == 1){
			return tbAddress;
		}else{
			 throw  new Exception();
		}  
	}
	/**
	 * 获取用户订单状态
	 * @return
	 */
	@Override
	public Object selectOrderSTatus(Long userid) {
		Map<String,Object>  map = new HashMap<String,Object>();
		// 查询商品信息
		TbOrderExample orderexample = new TbOrderExample();
		TbOrderExample.Criteria criteria = orderexample.createCriteria();
		criteria.andUserIdEqualTo(userid);
		List<TbOrder>  orderList = tbOrderMapper.selectByExample(orderexample);
		// '状态：1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭，7，退货中，8退货完成',

		int pay_num=0,rec_num=0,finish_num=0,refund_num=0;
		for (TbOrder tbOrder : orderList) {
			// 代付款
			if(tbOrder.getStatus()==1){
				pay_num++;
			}
			// 待收货
			if(tbOrder.getStatus()==2 || tbOrder.getStatus()==3|| tbOrder.getStatus()==4 ){
				rec_num++;
			}
			//已完成
			if(tbOrder.getStatus()==5){
				finish_num++;
			}
			//退货收货
			if(tbOrder.getStatus()==7||tbOrder.getStatus()==8){
				refund_num++;
			}
		}
		Map<String,Object>  orderInfo = new HashMap<String,Object>();
		orderInfo.put("pay_num",pay_num);
		orderInfo.put("rec_num",rec_num);
		orderInfo.put("finish_num",finish_num);
		orderInfo.put("refund_num",refund_num);
		map.put("orderInfo", orderInfo);
		
		return map;
	}
	/**
	 * 改变订单状态
	 */
	@Override
	public int updateOrderStatus(String orderId,String status,String remark) {
		TbOrder tbOrder = new TbOrder();
		tbOrder.setOrderId(orderId);
		if("cancel".equals(status)){
			tbOrder.setCloseTime(new Date());
			tbOrder.setStatus(6);
		}else if("receive".equals(status)){
			tbOrder.setEndTime(new Date());
			tbOrder.setStatus(5);
		}else if("refund".equals(status)){
			tbOrder.setStatus(7);
			tbOrder.setBuyerMessage(remark);
		}else if("paysuccess".equals(status)){
			tbOrder.setStatus(2);
			tbOrder.setPaymentTime(new Date());
		}
		tbOrder.setUpdateTime(new Date());
		return tbOrderMapper.updateByPrimaryKeySelective(tbOrder);
	}
	
	public void updateOrderPackageInfo(String orderId, String packageInfo){
		TbOrder tbOrder= tbOrderMapper.selectByPrimaryKey(orderId);
		tbOrder.setPackaeInfo(packageInfo);
		tbOrderMapper.updateByPrimaryKeySelective(tbOrder);
	}
	/**
	 * 获取订单详情
	 */
	@Override
	public Map<String,Object> selectOrderDetail(String orderId){
		Map<String,Object> result = new HashMap<String, Object>();
		// 获取订单信息
		TbOrder tborder= tbOrderMapper.selectByPrimaryKey(orderId);
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		if (tborder.getCartId() != null && !"".equals(tborder.getCartId())) {
			String cartIds[] = tborder.getCartId().split(",");
			for (String cartId : cartIds) {
				TbCart tbcart = tbCartMapper.selectByPrimaryKey(Long.parseLong(cartId));
				TbItem tbitem = tbItemMapper.selectByPrimaryKey(tbcart.getPid());
				// 商品信息
				Map<String,Object> mapItem = new HashMap<String, Object>();
				mapItem.put("photo_x", tbitem.getPhotoX().split(",")[0]);
				mapItem.put("name", tbitem.getName());
				mapItem.put("price", tbitem.getSprice());
				mapItem.put("num", tbcart.getNum());
				list.add(mapItem);	
			}

		}
		if(tborder!=null){
		// 根据订单信息获取收货人信息
		TbAddress tbAddress= tbAddressMapper.selectByPrimaryKey(tborder.getAddressId());
		if(tbAddress!=null){

			//收货人信息
			Map<String,Object> orderData = new HashMap<String, Object>();
			orderData.put("receiver", tbAddress.getName());
			orderData.put("tel", tbAddress.getTel());
			orderData.put("address_xq", tbAddress.getAddressXq());
			//订单信息
			DateTime dateTime=new DateTime(tborder.getCreateTime());  
			orderData.put("order_status", getStatus(Integer.toString(tborder.getStatus())));
			orderData.put("order_sn", tborder.getOrderId());
			orderData.put("addtime", dateTime.toString("yyyy/MM/dd HH:mm:ss"));
			orderData.put("remark", tborder.getBuyerMessage());
			orderData.put("payment",tborder.getPayment());
			orderData.put("postFee",tborder.getPostFee());
			orderData.put("shippingCode",tborder.getShippingCode());
			orderData.put("shippingName",tborder.getShippingName());

			result.put("pro", list);
			result.put("ord", orderData);
		}
		}
		return result;
	}
	/**
	 * 删除用户地址信息
	 */
	@Override
	public TaotaoResult deleteAddress(String userId, String addrId){
			TbAddressExample addressold = new TbAddressExample();
		TbAddressExample.Criteria criteriaold = addressold.createCriteria();
		criteriaold.andUidEqualTo(Long.parseLong(userId));
		criteriaold.andIdEqualTo(Integer.parseInt(addrId));
		int valueold = tbAddressMapper.deleteByExample(addressold);
		if(valueold == 1){
			return TaotaoResult.ok();
		}else{
			return TaotaoResult.fail();
		}  
	}
	/**
	 * 转换订单状态
	 * @param status
	 * @return
	 */
	private Object getStatus(String status){
		// '状态：1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭，7，退货中，8退货完成',
		switch (status) {
		case "1":
			return "未付款";
		case "2":
			return "已付款";
		case "3":
			return "未发货";
		case "4":
			return "已发货";
		case "5":
			return "交易成功";
		case "6":
			return "交易关闭";
		case "7":
			return "退货中";
		default :
			return "退货完成";

		}
	}
	/**
	 * 查询可支付订单
	 */
	@Override
	public TaotaoResult selectPayOrder(String orderId, String userId,String openId,String ip) {
		TbOrderExample tbOrderExample = new TbOrderExample();
		TbOrderExample.Criteria criteria = tbOrderExample.createCriteria();
		criteria.andOrderIdEqualTo(orderId);
		criteria.andUserIdEqualTo(Long.parseLong(userId));
		criteria.andStatusEqualTo(1);
		List<TbOrder> orderList = tbOrderMapper.selectByExampleWithBLOBs(tbOrderExample);
		if(orderList ==null || orderList.size()==0){
			return TaotaoResult.fail();
		}else{
			TbOrder tborder = orderList.get(0);
			WxPayServer wxpayserver = new WxPayServer();
			WxPayRequest wxpay = new WxPayRequest();
			wxpay.setAppid(APPID);
			wxpay.setOpenid(openId);
			wxpay.setTotalFee(Double.toString(tborder.getPayment()));
			wxpay.setAttach(tborder.getOrderId());
			wxpay.setBody(tborder.getCartId());
			wxpay.setSpbillCreateIp(ip);
			wxpay.setKey(MCHKEY);
			wxpay.setMchId(MCHID);
			wxpay.setNotifyUrl(NOTIFY_URL+tborder.getOrderId());
			Map<String, Object> result = wxpayserver.payServer(wxpay);
			WxPayRespones res = (WxPayRespones) result.get("data");
			this.updateOrderPackageInfo(orderId, res.getPackageInfo());
			return TaotaoResult.ok(result);
		}
	}

	@Override
	public int updateOrderStatus(String orderId) {
		// 修改订单状态
		TbOrder tbOrder= tbOrderMapper.selectByPrimaryKey(orderId);
		tbOrder.setOrderId(orderId);
		tbOrder.setPaymentTime(new Date());
		tbOrder.setStatus(2);
		int va = tbOrderMapper.updateByPrimaryKeySelective(tbOrder);
		// 修改商品信息
		TbCart cart = tbCartMapper.selectByPrimaryKey(Long.parseLong(tbOrder.getCartId()));
		TbItem tbItem = tbItemMapper.selectByPrimaryKey(cart.getPid());
		tbItem.setNum(tbItem.getNum()-Integer.parseInt(cart.getNum()));
		tbItem.setShiyong(tbItem.getShiyong()+Integer.parseInt(cart.getNum()));
		tbItem.setUpdated(new Date());
		TbItemExample itemExample = new TbItemExample();
		TbItemExample.Criteria itemcriteria = itemExample.createCriteria();
		itemcriteria.andIdEqualTo(tbItem.getId());
		int val = tbItemMapper.updateByExampleSelective(tbItem, itemExample);
		
		return val;
	}
	
	@Override
	public TbUser getUserByOpenId(Long userid) {
		TbUser TbUserList = tbUserMapper.selectByPrimaryKey(userid);
		return TbUserList;
	}
}

